Home:ALL Converter>I need to write a nested python dictionary to a text file using json, the text file is to be read as c++ dictionary (using OpenFOAM)

I need to write a nested python dictionary to a text file using json, the text file is to be read as c++ dictionary (using OpenFOAM)

Ask Time:2020-05-11T18:57:26         Author:kundan mishra

Json Formatter

Using json dump i wrote the text file, then removed double quotes and colons using python read write loops however i still have to add semicolons to each key value which i am not sure how to do. can any body suggest what would be the best way to do this.

This is how the dictionary(python) looks like

fvSolution={"FoamFile":{
                "version"  :    "2.0",
                "class"    : "dictionary",
            },
             "solvers":{
                "p" : {
                    "solver" :"PCG",
                    "preconditioner" :"DIC",
                    "tolerance" :1e-06,
                    "relTol" :0.01
                    }
                }
            }

This is how the text file looks like, i need to convert my dictionary to this

FoamFile
{
    version 2.0;
    class   dictionary;
    format  ascii;
}
solvers
{
    p
    {
        solver           PCG;
        preconditioner   DIC;
        tolerance        1e-06;
        relTol           0.01
    }
}

Here is my code:

# -*- coding: utf-8 -*-
"""
Created on Mon May 11 21:22:59 2020

@author: kundan
"""


import json 

#dictionary sample
fvSolution={
"FoamFile":{ 
"object" : "fvSolution" 
}, 
"solvers" :{ 
    "p" :{ 
        "solver" :"PCG", 
        } 
    } 
} 

#json object
a=json.dumps(fvSolution, indent=4, separators=("","\t")) 

#write json dump to afile
with open("fvSolution", "w") as outfile: 
    outfile.write(a) 

#read the file exported in previous step
f = open("fvSolution", "r") 
lines = f.readlines() 
f.close()

#write the dictionary after replace method
f=open("fvSolution","w") 
for line in lines: 
    line = line.replace('"', '') 
    f.write(line) 
f.close()

Author:kundan mishra,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61728051/i-need-to-write-a-nested-python-dictionary-to-a-text-file-using-json-the-text-f
yy